package com.miracle.moa.manager.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.miracle.common.Result;
import com.miracle.moa.manager.entity.User;
import com.miracle.moa.manager.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author miracle
 * @since 2021-03-22
 */
@RestController
@RequestMapping("/manager/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 根据用户名称查询用户详情
     *
     * @param username 用户名称
     * @return
     */
    @GetMapping("/load/{username}")
    public User findUserAndRole(@PathVariable("username") String username) {
        return userService.findUserAndRole(username);
    }


    /**
     * 查询用户列表
     * @param page
     * @param pageSize
     * @param searchUser
     * @return
     */
    @RequestMapping("/list")
    public IPage<User> listAllUser(@RequestParam(name = "page") int page,
                                   @RequestParam(name = "pageSize") int pageSize,
                                   @RequestParam(name = "searchUser") String searchUser) {
        User user = JSON.parseObject(searchUser, User.class);

        return userService.listAllUser(page, pageSize, user);
    }

    /**
     * 新增用户信息
     *
     * @param user
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result<User> save(@Validated @RequestBody User user) {
        return userService.saveUser(user);
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize(("hasAnyAuthority('admin')"))
    public Result<User> update(@Validated @RequestBody User user) {
        return userService.updateUser(user);
    }

    @DeleteMapping("/delete/{id}")
    @PreAuthorize(("hasAnyAuthority('admin')"))
    public Result delete(@PathVariable Integer id) {
        return userService.deleteUser(id);
    }
}
